<?php
/**
 * Created by PhpStorm.
 * User: zgh
 * Date: 2021-08-16
 * Time: 11:06
 */

namespace app\admin\middleware;

use app\admin\service\SystemLogService;


class SystemLogMiddleware
{

    /**
     * 敏感信息字段，日志记录时需要加密
     * @var array
     */
    protected $sensitiveParams = [
        'password',
        'password_again',
    ];

    /**
     * 对信息进行加密
     * @param $value
     * @return string
     */
    protected function password($value)
    {
        $value = sha1('sdsa') . md5($value) . md5('_encrypt') . sha1($value);
        return sha1($value);
    }

    public function handle($request, \Closure $next)
    {
        if ($request->isAjax()) {
            $method = strtolower($request->method());
            if (in_array($method, ['post', 'put', 'delete'])) {
                $url = $request->url();
                $ip = $request->ip();
                $params = $request->param();
                if (isset($params['s'])) {
                    unset($params['s']);
                }
                foreach ($params as $key => $val) {
                    in_array($key, $this->sensitiveParams) && $params[$key] = $this->password($val);
                }
                $data = [
                    'admin_id' => session('admin.id'),
                    'url' => $url,
                    'method' => $method,
                    'ip' => $ip,
                    'content' => json_encode($params, JSON_UNESCAPED_UNICODE),
                    'useragent' => $_SERVER['HTTP_USER_AGENT'],
                    'create_time' => time(),
                ];
                SystemLogService::instance()->save($data);
            }
        }
        return $next($request);
    }
}